<?php
namespace app\index\controller;
use app\parent\parents;
use think\Db;

class File extends parents
{
    // 展图
    public function files()
    {
        if(!$this->isAjax()){
            $view['info'] = $this->filesNav(0);
            return view('files',$view);
        }

        $page = $this->input('page',0);
        $pid = $this->input('pid',0);
        $where = '';
        if($pid){
            $where = ['agency_file_p_id' => $pid];
        }

        $page = $page * 60;

        $data = Db::name('agency_file')
        ->where('agency_file_w_id',$this->session('wid'))
        ->where('agency_file_a_id',$this->session('aid'))
        ->where('agency_file_is_show',1)
        ->where($where)
        ->order('id desc')
        ->limit($page.',60')
        ->field('id,agency_file_url as src,agency_file_p_title as title,agency_file_type as type,agency_file_w as w,agency_file_h as h')
        ->select();

        return $this->ajaxReturn(0,'',$data);

    }

    // 添加
    public function filesAdd()
    {
        $pid = $this->input('pid',0);
        $info = $this->input();
        if($pid == 0){
            $pid = Db::name('agency_file_type')
            ->where('agency_file_type_w_id',$this->session('wid'))
            ->where('agency_file_type_a_id',$this->session('aid'))
            ->where('agency_file_type_p_id',0)
            ->where('agency_file_type_is_show',1)
            ->value('id');
        }

        if(!$pid){
            return $this->ajaxReturn(1,'您还没有目录！','',0);
        }

        ini_set('memory_limit', '1024M');

        $files = request()->file('file');

        $ymd = date('Y_m_d');
      
        $file_str = '/web/images/'.$ymd.'/';
        $name_file = $this->wid.$this->session('uid').date('ymdHis');

        if(!file_exists(".".$file_str)){
            mkdir(".".$file_str);
        }

        $default = get_system();
        $info = [];
        foreach($files as $k => $file){

            // 移动到框架应用根目录/uploads/ 目录下
            $img = \think\Image::open($file);

            // 返回图片的类型
            $type = $img->type();

            $fileName = $name_file.$k.'.'.$type;
            $urlPath = $file_str.$fileName;

            $img->save('.'.$urlPath);
        
            $cosClient = new \Qcloud\Cos\Client(array('region' => $default['agency_system_yun_t_diqu'],'credentials'=> array(
                'secretId'    => $default['agency_system_yun_t_appid'],
                'secretKey' =>  $default['agency_system_yun_t_key'])));
            $result = $cosClient->Upload(
                $default['agency_system_yun_t_shuitong'],
                $fileName,
                fopen('.'.$urlPath, 'rb'));
            unlink('.'.$urlPath);
            
            $data = [
                'agency_file_w' => $img->width(),
                'agency_file_h' => $img->height(),
                'agency_file_type' => $type,
                'agency_file_url' => $fileName,
                'agency_file_p_id' => $pid,
                'agency_file_p_title' => $fileName,
                'agency_file_w_id' => $this->session('wid'),
                'agency_file_a_id' => $this->session('aid'),
                'agency_file_is_show' => 1,
                'agency_file_times' => time(),
            ];

            $info[$k]['id'] = Db::name('agency_file')->insertGetId($data);
            $info[$k]['src'] = $fileName;
            $info[$k]['title'] = $fileName;
            $info[$k]['w'] = $data['agency_file_w'];
            $info[$k]['h'] = $data['agency_file_h'];
        }

        return $this->ajaxReturn(1,'操作完成',$info);

    }

    public function filesNav($pid = 0)
    {
        $info = Db::name('agency_file_type')
        ->where('agency_file_type_w_id',$this->session('wid'))
        ->where('agency_file_type_a_id',$this->session('aid'))
        ->where('agency_file_type_p_id',$pid)
        ->where('agency_file_type_is_show',1)
        ->order('agency_file_type_sort asc')
        ->select();

        $str = '';
        if($info){
            foreach($info as $k => $v){
                $str .= '<li onclick="addimg('.$v['id'].')">'.$v['agency_file_type_p_title'].'</li>';
            }
        }
        return $str;
    }

    public function fileAdd($table = 'agency_file')
    {
        ini_set('memory_limit', '1024M');
        $info = $this->input(['pic','zoom'],'');
        
        $file = $this->base64_file($info['pic'],$info['zoom']);
        $data['agency_file_w'] = $file['agency_file_w'];
        $data['agency_file_h'] = $file['agency_file_h'];
        $data['agency_file_type'] = $file['agency_file_type'];

        $default = get_system();
        
        $cosClient = new \Qcloud\Cos\Client(array('region' => $default['agency_system_yun_t_diqu'],'credentials'=> array(
            'secretId'    => $default['agency_system_yun_t_appid'],
            'secretKey' =>  $default['agency_system_yun_t_key'])));
        $result = $cosClient->Upload(
            $default['agency_system_yun_t_shuitong'],
            $file['key'],
            fopen('.'.$file['agency_file_url'], 'rb'));
        unlink('.'.$file['agency_file_url']);
        $data['agency_file_url'] = $file['key'];
        $data['agency_file_p_title'] = $file['key'];
        $data['agency_file_p_id'] = $this->input('pid');

        $data['agency_file_w_id'] = $this->session('wid');
        $data['agency_file_a_id'] = $this->session('aid');
        $data['agency_file_is_show'] = 1;
        $data['agency_file_times'] = time();

        $return['id'] = Db::name($table)->insertGetId($data);
        $return['src'] = $file['key'];
        $return['title'] = $file['key'];
        $return['w'] = $data['agency_file_w'];
        $return['h'] = $data['agency_file_h'];

        if($return['id']){
            return $this->ajaxReturn(0,'操作成功',$return);
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
        
    }

    public function fileDel($table = 'agency_file')
    {
        $id = $this->input('id',0); // 获取id
        
        $is = Db::name($table)->where('id','in',$id)->delete();

        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
        
    }

    /**
     *  保存base64图片到图片库
     *  $name = 图片名称
     *  $str  = 不存在请求参数下标
     *  $arr  = 如果多张是否返回数组
     */
    public function base64_file($pic,$zoom = 1,$type = '')
    {
        $file_str = '/web/images/file/';
        $name_file = date('YmdHis').$this->wid.$this->session('uid');

        if(!file_exists(".".$file_str)){
            mkdir(".".$file_str);
        }

        $pic = explode(',',$pic);
        $pic_type = explode('/',explode(';',$pic[0])[0])[1];
        $pic_type = $pic_type == 'jpeg' ? 'jpg' : $pic_type;

        $pic_str = $file_str.$name_file.'.'.$pic_type;
        $pic_file = $pic[count($pic)-1];
        file_put_contents('.'.$pic_str,base64_decode($pic_file));

        if(file_exists(".".$pic_str) && is_file(".".$pic_str)){
            $image = \think\Image::open('.'.$pic_str);
            // 返回图片的宽度
            $arr['agency_file_w'] = $image->width(); 
            // 返回图片的高度
            $arr['agency_file_h'] = $image->height(); 
            // 返回图片的类型
            $arr['agency_file_type'] = $image->type();

            $image->save('.'.$pic_str,$arr['agency_file_type'],$zoom);
            $arr['agency_file_url'] = $pic_str;
            $arr['key'] = $name_file.'.'.$pic_type;
        }else{
            $arr['agency_file_url'] = '';
            $arr['agency_file_w'] = '';
            $arr['agency_file_h'] = '';
            $arr['agency_file_type'] = '';
            $arr['key'] = '';
        }
           
        return $arr;
    }

    // 文件列表
    public function type($table = 'agency_file_type')
    {
        if(!$this->isAjax()){
            $data['info'] = $this->retype();
            return view('type',$data);
        }

        $where = $this->whereSql([
            'eq' => ['agency_file_type_p_id'],
        ]);
        
        $pa = $this->input(['page','limit'],1);
        $page = ($pa['page'] - 1) * $pa['limit'];
        
        $data = Db::name($table)
            ->where($where)
            ->where('agency_file_type_w_id',$this->wid)
            ->order('agency_file_type_sort asc')
            ->limit($page,$pa['limit'])
            // ->fetchSql(true)
            ->select();
        
        $count = Db::name($table)
            ->where($where)
            ->where('agency_file_type_w_id',$this->wid)
            ->count('id');

        return $this->ajaxReturn(0,'',$data,$count);
        
    }

    public function retype($pid = 0,$arr = [],$str = '')
    {
        $info = Db::name('agency_file_type')
            ->where('agency_file_type_w_id',$this->wid)
            ->where('agency_file_type_p_id',$pid)
            ->order('agency_file_type_sort asc')
            ->select();
        if($info){
            foreach ($info as $k => $v) {
                $v['agency_file_type_p_title'] = $str . $v['agency_file_type_p_title'];
                $arr[] = $v;

                $arr = $this->retype($v['id'],$arr,$str . '|------');
            }
        }

        return $arr;
    }

    public function typeAdd($table = 'agency_file_type')
    {
        if (!$this->isPost()) {
            $viewArr['info'] = $this->retype();
            return view('typeAdd',$viewArr);
        }

        $data = $this->unInput('id');

        $data['agency_file_type_w_id'] = $this->session('wid');
        $data['agency_file_type_a_id'] = $this->session('aid');
        $data['agency_file_type_times'] = time();
        $is = Db::name($table)->insert($data);

        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

    public function typeUp($table = 'agency_file_type')
    {
        $id = $this->input('id');
        if (!$this->isPost()) {
            $viewArr['data'] = Db::name($table)->where('id',$id)->find();
            $viewArr['info'] = $this->retype();
            return view('typeUp',$viewArr);
        }

        $data = $this->unInput('id');

        $is = Db::name($table)->where('id',$id)->update($data);

        if($is){
            return $this->ajaxReturn(0,'操作成功');
        }else{
            return $this->ajaxReturn(1,'操作失败');
        }
    }

    
}
